<template>
    <div style="margin: 0 5px;transition: all 3s;">
        <div v-if="!practices.length">该题目下暂无习题</div>
        <div v-else>
            <div v-if="ids.size > 0"
                style="text-align: center;margin: 20px 0;padding: 20px 5px;font-size: 12px;border-radius: 5px;cursor: pointer;background-color: #fafafa;">
                <span @click="inputPaper"><i class="el-icon-upload"></i>&nbsp立即入卷</span>
            </div>
            <div v-for="(practice, index) in practices" :key="index">
                <div class="item-practice">
                    <div>
                        <span style="margin-right: 10px;font-size: 14px;">第{{ index + 1 }}题</span>
                        <span class="practice-type">题型：{{ practiceTypeChange(practice.practiceType) }}</span>
                        <span class="practice-type">科属：{{ practice.projectName }}</span>
                        <el-checkbox :disabled="haveBind(practice, paperInfo.id) !== undefined"
                            @change="putPaper(practice)" v-model="practice.isCheck">入卷
                            <span style="color: brown;margin: 0 5px;font-size: 12px;"
                                v-if="haveBind(practice, paperInfo.id) !== undefined">[已添加，不可选中]</span>
                        </el-checkbox>
                    </div>
                    <div v-html="practice.askItem"></div>
                </div>
            </div>
            <div style="padding: 30px 0;">
                <el-pagination @current-change="handleCurrentChange" :page-size="size" layout="total, prev, pager, next"
                    :total="total">
                </el-pagination>
            </div>
        </div>
    </div>
</template>
<script>
export default {
    data() {
        return {
            paperInfo: {},
            practices: [],
            selectedList: [],
            paperPracticeList: [],
            ids: new Set(),
            total: 0,
            size: 8,
            current: 1
        }
    },
    created() {
        this.defaultLoad();
    },
    methods: {
        async inputPaper() {
            const confirmed = await this.$swalConfirm({
                title: '题目添加',
                text: `是否将选中题目加入卷子中？`,
                icon: 'info',
            });
            if (confirmed) {
                let paperPractices = [];
                for (const practiceId of this.ids) {
                    const paperPractice = {
                        paperId: this.paperInfo.id,
                        practiceId: practiceId
                    }
                    paperPractices.push(paperPractice);
                }
                // 批量绑定题目
                this.$axios.post(`/paper-practice/batchSave`, paperPractices).then(response => {
                    const { data } = response;
                    if (data.code === 200) {
                        this.defaultLoad();
                        this.$swal.fire({
                            title: '题目绑定',
                            text: '绑定成功',
                            icon: 'success',
                            showConfirmButton: false,
                            timer: 1000,
                        });
                        this.$emit('to-self', true);
                    }
                })
            }
        },
        putPaper(practice) {
            if (practice.isCheck) {
                if (!this.ids.has(practice.id)) {
                    this.ids.add(practice.id);
                }
            } else {
                this.ids.delete(practice.id);
            }
        },
        defaultLoad() {
            this.loadPaperInfo().then(() => {
                this.loadPracticeList();
                this.loadSelfPracticeList(this.paperInfo.id);
            }).catch(error => {
                console.error('加载试卷信息失败:', error);
            });
        },
        practiceTypeChange(type) {
            if (type === 1) {
                return '单选题';
            } else if (type === 2) {
                return "多选题";
            } else if (type === 3) {
                return "填空题";
            } else {
                return "判断题";
            }
        },
        haveBind(practice, paperId) {
            return this.paperPracticeList.find(
                entity => entity.paperId === paperId &&
                    entity.practiceId === practice.id
            );
        },
        // 解析卷子信息
        async loadPaperInfo() {
            return new Promise((resolve, reject) => {
                const paperJson = sessionStorage.getItem('paperInfo');
                try {
                    if (paperJson) {
                        this.paperInfo = JSON.parse(paperJson);
                        resolve();
                    } else {
                        reject(new Error('试卷信息未找到或格式不正确'));
                    }
                } catch (e) {
                    reject(e);
                }
            })
        },
        handleCurrentChange(current) {
            this.current = current;
            this.loadPracticeList();
        },
        // 加载科目下全部的题目
        loadPracticeList() {
            const projectQueryDto = {
                projectId: this.paperInfo.projectId,
                size: this.size,
                current: this.current
            }
            this.$axios.post(`/practice/query`, projectQueryDto).then(response => {
                const { data } = response;
                if (data.code === 200) {
                    this.practices = [];
                    this.practices = data.data;
                    this.total = data.total;
                }
            })
        },
        // 加载试卷现有的题目列表
        loadSelfPracticeList(paperId) {
            const paperPracticeQueryDto = {
                paperId: paperId
            }
            this.$axios.post(`/paper-practice/query`, paperPracticeQueryDto).then(response => {
                const { data } = response;
                if (data.code === 200) {
                    this.paperPracticeList = data.data;
                }
            })
        },
    }
};
</script>
<style scoped lang="scss">
.item-practice {
    padding: 10px 0px;
    margin: 20px 0;
    cursor: pointer;
    background-color: #fff;
    border-radius: 3px;
}

.practice-type {
    margin-right: 10px;
    display: inline-block;
    padding: 3px 5px;
    border-radius: 3px;
    background-color: rgb(235, 237, 245);
    color: rgb(43, 121, 203);
    font-size: 12px;
}
</style>